package com.xbongbong.paas.business.rule;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.FormDataFormExplainHelper;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.pojo.dto.CoUserListDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.businessrule.pojo.dto.OperationDTO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.domain.entity.UpdateDataValueEntity;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.form.pojo.RuleTargetPojo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author 吴峰
 * @version v1.0
 * @date 2019/12/3 21:44
 * @since v1.0
 */
@Component
public class BusinessRuleUserPermissionHelp {

    @Resource
    private FormDataFormExplainHelper formDataFormExplainHelper;

    @Resource
    private PackageHelp packageHelp;


    /**
     * 校验版本以及白名单
     * @param corpid
     * @return true：不可以使用业务规则；false：可以使用
     * @throws XbbException
     */
    public boolean validateUsePermission(String corpid) throws XbbException {

        Integer feeType = getFeeType(corpid);
//        Object value = companyConfigService.getByConfigAlias(CompanyConfigEnum.BUSINESS_RULE_WHITE.getAlias(), RedisPrefixConstant.BUSINESS_RULE, CompanyConfigEnum.BUSINESS_RULE_WHITE.getAlias(), "0", TimeConstant.SECONDS_PER_DAY);
//        if (Objects.nonNull(value)) {
//            List<String> corpidList = JSON.parseArray(value.toString(), String.class);
//            if (CollectionsUtil.isNotEmpty(corpidList) && !corpidList.contains(corpid)) {
//                // 不在白名单内，不允许使用
//                return true;
//            }
//        }
        if (Objects.equals(feeType, 0)) {
            return true;
        } else if (Objects.equals(feeType, 1)) {
            // 高级版有五对业务规则
            return false;
        } else if (!PackageTypeEnum.isProfessionalPackage(feeType)) {
            // 旗舰版可以使用
            return false;
        }
        return true;
    }

    /**
     * 获取版本
     * @param corpid
     * @return
     * @throws XbbException
     */
    public Integer getFeeType(String corpid) throws XbbException {
        return  packageHelp.getFeeType(corpid);
    }

    public void validateFieldCanEdit(OperationDTO operationDTO, List<UpdateDataEntity> updateList, List<PaasFormDataEntityExt> formDataList) throws XbbException {
        Set<Long> dataIdSet = new HashSet<>();
        updateList.forEach(item->{
            dataIdSet.add(item.getId());
        });
        String corpid = operationDTO.getCorpid();
        RuleTargetPojo ruleTargetPojo = operationDTO.getTarget();
        List<Long> dataIdList = new ArrayList<>(dataIdSet);
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Integer businessType = ruleTargetPojo.getLinkBusinessType();
        Boolean hasTeam = UserTeamEnum.hasTeam(businessType);
        if (hasTeam){
            formDataFormExplainHelper.getUserIdMap(dataIdList,corpid,businessType,false,mainUserMap,coUserMap);
        } else {
            CoUserListDTO coUserListDTO = new CoUserListDTO();
            coUserListDTO.setCorpid(corpid);
            coUserListDTO.setFormId(ruleTargetPojo.getFormId());
            coUserListDTO.setFormDataIdIn(dataIdList);
//            coUserMap = coUserService.coUserMap(coUserListDTO);
        }
        Map<Long, PaasFormDataEntityExt> formDataMap = new HashMap<>(formDataList.size());
        formDataList.forEach(item->{
            formDataMap.put(item.getDataId(), item);
        });
        Map<String, FieldAttrEntity> explainMap = operationDTO.getTargetExplain();
        Map<Long, List<String>> finalCoUserMap = coUserMap;
        Iterator<UpdateDataEntity> updateIterator = updateList.iterator();
        while (updateIterator.hasNext()) {
            UpdateDataEntity item = updateIterator.next();
            Long dataId = item.getId();
            List<UpdateDataValueEntity> updateDataEntities = item.getData();
            Iterator<UpdateDataValueEntity> iterator = updateDataEntities.iterator();
            while (iterator.hasNext()) {
                UpdateDataValueEntity updateDataValueEntity = iterator.next();
                String key = updateDataValueEntity.getKey().replace("$.", "");
                FieldAttrEntity fieldAttrEntity = explainMap.get(key);
                if (Objects.equals(0, fieldAttrEntity.getVisible())) {
                    iterator.remove();
                    continue;
                }
                if (Objects.equals(0, fieldAttrEntity.getEditable())) {
                    iterator.remove();
                    continue;
                }
                if (Objects.nonNull(fieldAttrEntity)) {
                    // 负责人，协同人
                    List<String> mainUserList = mainUserMap.get(dataId);
                    List<String> coUserList = finalCoUserMap.get(dataId);
                    HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
                    handlerExplainDTO.setUserId(operationDTO.getUserId());
                    handlerExplainDTO.setLoginUser(operationDTO.getLoginUser());
                    // 获取对应数据
                    PaasFormDataEntityExt formData = formDataMap.get(dataId);
                    handlerExplainDTO.setCreatorId(formData.getCreatorId());
                    // 设置创建人
                    if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType)) {
                        handlerExplainDTO.setCreatorId(formData.getData().getString(CustomerManagementEnum.CREATOR.getAttr()));
                    } else {
                        handlerExplainDTO.setCreatorId(formData.getCreatorId());
                    }
                    if (hasTeam) {
                        handlerExplainDTO.setOwnerId(mainUserList);
                    } else {
                        handlerExplainDTO.setOwnerId(Collections.singletonList(formData.getOwnerId()));
                    }
                    if (coUserList != null && !coUserList.isEmpty()) {
                        handlerExplainDTO.setCoUserId(coUserList);
                    }
                    Boolean invisible = ExplainUtil.invisibleOfScope(fieldAttrEntity, handlerExplainDTO);
                    if (invisible) {
                        // 不可见
                        iterator.remove();
                        continue;
                    }
                    Boolean notEdit = ExplainUtil.isEditableOfScope(fieldAttrEntity, handlerExplainDTO);
                    if (!notEdit) {
                        // 不可编辑
                        iterator.remove();
                        continue;
                    }
//                    if (ExplainUtil.isSubForm(fieldAttrEntity.getFieldType())) {
//                        JSONArray jsonArray = fieldAttrEntity.getSubForm().getItems();
//                        Map<String, FieldAttrEntity> subExplainMap = ExplainUtil.getExplainMap(JSON.toJSONString(jsonArray), null);
//                        fieldAttrEntity = subExplainMap.get(targetSubAttr);
//                        invisible = ExplainUtil.invisibleOfScope(fieldAttrEntity, handlerExplainDTO);
//                        if (invisible) {
//                            // 不可见
//                            iterator.remove();
//                            continue;
//                        }
//                        notEdit = ExplainUtil.isEditableOfScope(fieldAttrEntity, handlerExplainDTO);
//                        if (!notEdit) {
//                            // 不可编辑
//                            iterator.remove();
//                            continue;
//                        }
//                    }
                }
            }
            if (CollectionsUtil.isEmpty(updateDataEntities)){
                updateIterator.remove();
            }
        }
    }
}
